package org.example.server.service;

import cn.hutool.core.util.IdUtil;
import cn.hutool.crypto.digest.DigestUtil;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.example.server.bean.AccountBean;
import org.example.server.mapper.AccountMapper;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class AccountService {

    @Resource
    private AccountMapper accountMapper;

    public void save(AccountBean accountBean){
        log.debug("用户注册，检查参数完整度");
        if (accountBean.getUsername() == null){
            throw new RuntimeException("用户名不能为空");
        }
        if (accountBean.getPassword()==null){
            throw new RuntimeException("密码不能为空");
        }
        if (!accountBean.getPassword().equals(accountBean.getRePassword())){
            throw new RuntimeException("两次密码不一致");
        }

        log.debug("用户注册，根据用户名查询用户信息， 校验用户名是否重复");
        AccountBean resultBean = accountMapper.selectByName(accountBean);
        if (resultBean != null){
            throw new RuntimeException("用户名已经被占用");
        }

        log.debug("用户注册，补充必要参数");
        // 使用工具生成一个Long型的随机不会重复的ID值
        accountBean.setId(IdUtil.getSnowflakeNextId());
        // 将密码使用md算法转成一个新的字符串串
        accountBean.setPassword(DigestUtil.md5Hex(accountBean.getPassword()));
        accountBean.setUpdateTime(System.currentTimeMillis());
        accountBean.setCreateTime(System.currentTimeMillis());

        log.debug("用户注册，保存用户信息");
        int inserted = accountMapper.insert(accountBean);
        if (inserted <= 0){
            throw new RuntimeException("用户注册失败");
        }

    }

    public void login(AccountBean accountBean){
        log.debug("用户登录，根据用户名查询用户信息");
        if (accountBean.getUsername()==null || accountBean.getPassword()==null){
            throw new RuntimeException("用户名或密码错误");
        }
        log.debug("用户登录，根据用户名查询账户信息");
        AccountBean resultBean = accountMapper.selectByName(accountBean);
        if (resultBean==null){
            throw new RuntimeException("用户名或密码错误");
        }

        log.debug("用户登录，校验密码是否正确");
        String password = accountBean.getPassword();
        String md5Password = DigestUtil.md5Hex(password);
        if (!resultBean.getPassword().equals(md5Password)){
            throw new RuntimeException("用户名或密码错误");
        }



    }

}
